const normalizeColor = (color) => {
    if (!color) return '';
    if (color.includes('#')) {
        if (color.length === 4) return `${color}${color.slice(1)}`;
        if (color.length < 7) return '';
        return color;
    }
    // 将颜色字符串转换为小写
    color = color.toLowerCase();
    if (color.indexOf('rgb') === 0) {
        // 如果是以rgb或rgba开头的格式，则将其转换为#开头的格式
        const match = /rgba?\((\d+),\s*(\d+),\s*(\d+)(,\s*\d+\.\d+)?\)/.exec(color);
        if (match) {
            // eslint-disable-next-line radix
            const r = parseInt(match[1]);
            // eslint-disable-next-line radix
            const g = parseInt(match[2]);
            // eslint-disable-next-line radix
            const b = parseInt(match[3]);
            // eslint-disable-next-line no-bitwise
            return `#${(r << 16 | g << 8 | b).toString(16).padStart(6, '0')}`;
        }
    }
    // 如果无法解析颜色，则返回空字符串
    return '';
};

const getTintColor = (color, tint) => {
    let red = parseInt(color.slice(0, 2), 16);
    let green = parseInt(color.slice(2, 4), 16);
    let blue = parseInt(color.slice(4, 6), 16);

    // when primary color is in its rgb space
    if (tint === 0) return `#${color}`;
    red += Math.round(tint * (255 - red));
    green += Math.round(tint * (255 - green));
    blue += Math.round(tint * (255 - blue));

    return `#${red.toString(16)}${green.toString(16)}${blue.toString(16)}`;
};

const getShadeColor = (color, shade) => {
    let red = parseInt(color.slice(0, 2), 16);
    let green = parseInt(color.slice(2, 4), 16);
    let blue = parseInt(color.slice(4, 6), 16);

    red = Math.round((1 - shade) * red);
    green = Math.round((1 - shade) * green);
    blue = Math.round((1 - shade) * blue);
    const clear = (s) => `0${s}`.slice(-2);

    return `#${clear(red.toString(16))}${clear(green.toString(16))}${clear(blue.toString(16))}`;
};
// 获取阶梯颜色列表
const getThemeClusters = (color) => {
    // 将color转换为 #xxxxxx
    color = normalizeColor(color).replace('#', '');
    if (!color) return [];
    const clusters = [getShadeColor(color, 0.1)];
    Array(10).fill().forEach((_, i) => clusters.push(getTintColor(color, Number((i / 10).toFixed(2)))));
    return clusters.reverse();
};

const setRootThemeColor = (color) => {
    if (!color) return;
    let rootTag = document.getElementById('root-style');
    if (!rootTag) {
        rootTag = document.createElement('style');
        rootTag.setAttribute('id', 'root-style');
        document.head.appendChild(rootTag);
    }
    const colorClusters = getThemeClusters(color);
    const clusters = colorClusters.slice(0, 9).reverse();
    rootTag.innerText = `:root {
        --color-primary: ${color};
        ${clusters.map((c, i) => `--color-primary-light-${i + 1}: ${c || ''};`).join('\n')}
        --el-color-primary: ${color};
        ${clusters.map((c, i) => `--el-color-primary-light-${i + 1}: ${c || ''};`).join('\n')}
        --el-primary-color: ${color};
        ${clusters.map((c, i) => `--el-primary-color-light-${i + 1}: ${c || ''};`).join('\n')}
        --el-color-primary-dark-2: ${colorClusters[10]};
    }`;
};

const changeThemeColor = (color) => {
    const storageThemeColor = window.localStorage.getItem('current_theme_color');
    color = color || storageThemeColor || '';
    window.localStorage.setItem('current_theme_color', color);
    setRootThemeColor(color);
};

const resetThemeColor = () => {
    const rootTag = document.getElementById('root-style');
    rootTag.innerHTML = '';
    window.localStorage.setItem('current_theme_color', '');
};

export {
    getThemeClusters,
    resetThemeColor,
    changeThemeColor,
};
